/**
 * 本地存储工具类
 * 提供统一的存储接口，支持自动序列化和错误处理
 */

// 存储键名常量
export const STORAGE_KEYS = {
  // 认证相关
  TOKEN: 'auth_token',
  USER_INFO: 'user_info',
  REFRESH_TOKEN: 'refresh_token',
  LOGIN_TIME: 'login_time',
  EXPIRES_IN: 'expires_in',

  // 应用设置
  THEME: 'app_theme',
  LANGUAGE: 'app_language',

  // 表单缓存
  LOGIN_FORM_DATA: 'login_form_data',
  SELECTED_ROLE: 'selected_role',

  // 用户偏好
  REMEMBER_USERNAME: 'remember_username',
  AUTO_LOGIN: 'auto_login'
}

/**
 * 存储管理类
 */
export class StorageManager {
  /**
   * 设置存储项
   * @param key 存储键
   * @param value 存储值
   */
  static set<T>(key: string, value: T): boolean {
    try {
      // 字符串类型直接存储，避免额外的双引号
      // 其他类型使用JSON.stringify序列化
      const serializedValue = typeof value === 'string' ? value : JSON.stringify(value)
      uni.setStorageSync(key, serializedValue)
      return true
    } catch (error) {
      console.error(`存储失败 [${key}]:`, error)
      return false
    }
  }

  /**
   * 获取存储项
   * @param key 存储键
   * @param defaultValue 默认值
   */
  static get<T>(key: string, defaultValue?: T): T | null {
    try {
      const value = uni.getStorageSync(key)
      if (value !== undefined && value !== null && value !== '') {
        // 尝试JSON.parse，如果失败则直接返回原值
        try {
          return JSON.parse(value)
        } catch {
          // JSON.parse失败，说明原值就是字符串（如Token）
          return value as T
        }
      }
      return defaultValue || null
    } catch (error) {
      console.error(`读取失败 [${key}]:`, error)
      return defaultValue || null
    }
  }

  /**
   * 移除存储项
   * @param key 存储键
   */
  static remove(key: string): boolean {
    try {
      uni.removeStorageSync(key)
      return true
    } catch (error) {
      console.error(`删除失败 [${key}]:`, error)
      return false
    }
  }

  /**
   * 清空所有存储
   */
  static clear(): boolean {
    try {
      uni.clearStorageSync()
      return true
    } catch (error) {
      console.error('清空存储失败:', error)
      return false
    }
  }

  /**
   * 检查存储项是否存在
   * @param key 存储键
   */
  static has(key: string): boolean {
    try {
      const value = uni.getStorageSync(key)
      return value !== ''
    } catch (error) {
      console.error(`检查存储项失败 [${key}]:`, error)
      return false
    }
  }

  /**
   * 获取所有存储键名
   */
  static keys(): string[] {
    try {
      const info = uni.getStorageInfoSync()
      return info.keys || []
    } catch (error) {
      console.error('获取存储键名失败:', error)
      return []
    }
  }

  /**
   * 获取存储信息
   */
  static getInfo(): any {
    try {
      return uni.getStorageInfoSync()
    } catch (error) {
      console.error('获取存储信息失败:', error)
      return {
        keys: [],
        currentSize: 0,
        limitSize: 0
      }
    }
  }
}

/**
 * 认证存储管理类
 */
export class AuthStorage {
  /**
   * 保存认证信息
   * @param token 访问令牌
   * @param userInfo 用户信息
   * @param refreshToken 刷新令牌
   * @param expiresIn 过期时间（秒）
   */
  static saveAuthInfo(
    token: string,
    userInfo: any,
    refreshToken?: string,
    expiresIn?: number
  ): boolean {
    const loginTime = Date.now()

    const success = StorageManager.set(STORAGE_KEYS.TOKEN, token) &&
                    StorageManager.set(STORAGE_KEYS.USER_INFO, userInfo) &&
                    StorageManager.set(STORAGE_KEYS.LOGIN_TIME, loginTime)

    if (refreshToken) {
      StorageManager.set(STORAGE_KEYS.REFRESH_TOKEN, refreshToken)
    }

    if (expiresIn) {
      StorageManager.set(STORAGE_KEYS.EXPIRES_IN, expiresIn)
    }

    return success
  }

  /**
   * 获取认证信息
   */
  static getAuthInfo() {
    return {
      token: StorageManager.get(STORAGE_KEYS.TOKEN),
      userInfo: StorageManager.get(STORAGE_KEYS.USER_INFO),
      refreshToken: StorageManager.get(STORAGE_KEYS.REFRESH_TOKEN),
      loginTime: StorageManager.get(STORAGE_KEYS.LOGIN_TIME),
      expiresIn: StorageManager.get(STORAGE_KEYS.EXPIRES_IN)
    }
  }

  /**
   * 清除认证信息
   */
  static clearAuthInfo(): boolean {
    return StorageManager.remove(STORAGE_KEYS.TOKEN) &&
           StorageManager.remove(STORAGE_KEYS.USER_INFO) &&
           StorageManager.remove(STORAGE_KEYS.REFRESH_TOKEN) &&
           StorageManager.remove(STORAGE_KEYS.LOGIN_TIME) &&
           StorageManager.remove(STORAGE_KEYS.EXPIRES_IN)
  }

  /**
   * 检查是否已登录
   */
  static isLoggedIn(): boolean {
    const authInfo = this.getAuthInfo()

    if (!authInfo.token || !authInfo.loginTime) {
      return false
    }

    // 检查Token是否过期
    const currentTime = Date.now()
    const expireTime = authInfo.loginTime + (authInfo.expiresIn || 7200) * 1000

    return currentTime < expireTime
  }

  /**
   * 检查Token是否即将过期（5分钟内）
   */
  static isTokenExpiringSoon(): boolean {
    const authInfo = this.getAuthInfo()

    if (!authInfo.loginTime || !authInfo.expiresIn) {
      return true
    }

    const currentTime = Date.now()
    const expireTime = authInfo.loginTime + authInfo.expiresIn * 1000
    const fiveMinutes = 5 * 60 * 1000

    return (expireTime - currentTime) <= fiveMinutes
  }

  /**
   * 获取用户显示名称
   */
  static getUserDisplayName(): string {
    const userInfo = StorageManager.get(STORAGE_KEYS.USER_INFO)
    return userInfo?.name || userInfo?.username || '未知用户'
  }

  /**
   * 获取用户角色
   */
  static getUserRole(): string | null {
    const userInfo = StorageManager.get(STORAGE_KEYS.USER_INFO)
    return userInfo?.role || null
  }

  /**
   * 获取用户头像
   */
  static getUserAvatar(): string {
    const userInfo = StorageManager.get(STORAGE_KEYS.USER_INFO)
    return userInfo?.avatar || '/static/logo.png'
  }
}

/**
 * 应用设置存储管理类
 */
export class SettingsStorage {
  /**
   * 保存主题设置
   */
  static setTheme(theme: 'light' | 'dark'): boolean {
    return StorageManager.set(STORAGE_KEYS.THEME, theme)
  }

  /**
   * 获取主题设置
   */
  static getTheme(): 'light' | 'dark' {
    return StorageManager.get(STORAGE_KEYS.THEME, 'light') || 'light'
  }

  /**
   * 保存语言设置
   */
  static setLanguage(language: string): boolean {
    return StorageManager.set(STORAGE_KEYS.LANGUAGE, language)
  }

  /**
   * 获取语言设置
   */
  static getLanguage(): string {
    return StorageManager.get(STORAGE_KEYS.LANGUAGE, 'zh-CN') || 'zh-CN'
  }

  /**
   * 保存记住用户名设置
   */
  static setRememberUsername(username: string): boolean {
    return StorageManager.set(STORAGE_KEYS.REMEMBER_USERNAME, username)
  }

  /**
   * 获取记住的用户名
   */
  static getRememberUsername(): string {
    return StorageManager.get(STORAGE_KEYS.REMEMBER_USERNAME, '') || ''
  }

  /**
   * 保存自动登录设置
   */
  static setAutoLogin(enabled: boolean): boolean {
    return StorageManager.set(STORAGE_KEYS.AUTO_LOGIN, enabled)
  }

  /**
   * 获取自动登录设置
   */
  static getAutoLogin(): boolean {
    return StorageManager.get(STORAGE_KEYS.AUTO_LOGIN, false) || false
  }
}

/**
 * 表单缓存存储管理类
 */
export class FormCacheStorage {
  /**
   * 保存登录表单数据
   */
  static saveLoginForm(formData: {
    username: string
    role: string
  }): boolean {
    return StorageManager.set(STORAGE_KEYS.LOGIN_FORM_DATA, formData)
  }

  /**
   * 获取登录表单数据
   */
  static getLoginForm(): {
    username: string
    role: string
  } {
    return StorageManager.get(STORAGE_KEYS.LOGIN_FORM_DATA, {
      username: '',
      role: ''
    })
  }

  /**
   * 清除登录表单缓存
   */
  static clearLoginForm(): boolean {
    return StorageManager.remove(STORAGE_KEYS.LOGIN_FORM_DATA)
  }

  /**
   * 保存选择的角色
   */
  static setSelectedRole(role: string): boolean {
    return StorageManager.set(STORAGE_KEYS.SELECTED_ROLE, role)
  }

  /**
   * 获取选择的角色
   */
  static getSelectedRole(): string | null {
    return StorageManager.get(STORAGE_KEYS.SELECTED_ROLE)
  }

  /**
   * 清除选择的角色
   */
  static clearSelectedRole(): boolean {
    return StorageManager.remove(STORAGE_KEYS.SELECTED_ROLE)
  }
}

// 导出便捷方法
export const storage = StorageManager
export const authStorage = AuthStorage
export const settingsStorage = SettingsStorage
export const formCache = FormCacheStorage